package cn.wizzer.app.user.modules.service.impl;

import cn.wizzer.app.user.modules.models.GroupInfo;
import cn.wizzer.app.user.modules.models.GroupLog;
import cn.wizzer.app.user.modules.models.User;
import cn.wizzer.app.user.modules.models.enums.MsgTypeEnum;
import cn.wizzer.app.user.modules.models.enums.OprTypeEnum;
import cn.wizzer.app.user.modules.models.vo.GroupMsgVO;
import cn.wizzer.app.user.modules.services.GroupInfoService;
import cn.wizzer.app.user.modules.services.GroupRecordService;
import cn.wizzer.app.user.modules.services.UserService;
import cn.wizzer.framework.base.service.BaseServiceImpl;
import cn.wizzer.framework.base.service.CommonDBService;
import cn.wizzer.framework.page.Pagination;
import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSONObject;
import org.nutz.dao.Cnd;
import org.nutz.dao.Dao;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Sql;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.lang.Times;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@IocBean(args = {"refer:dao"})
@Service(interfaceClass = GroupRecordService.class)
public class GroupRecordServiceImpl extends BaseServiceImpl<GroupLog> implements GroupRecordService {
    public GroupRecordServiceImpl(Dao dao) {
        super(dao);
    }

    @Inject
    private CommonDBService dbService;
    @Inject
    private UserService userService;
    @Inject
    private GroupInfoService groupInfoService;

    @Override
    public Pagination listPage(int pageNumber, int pageSize, String groupName, String userKeyword, String[] searchDate, MsgTypeEnum msgType, OprTypeEnum oprType) {
        //用户集合map
        Map<String, String> userMap = new HashMap<>();
        //群组集合map
        Map<String, String> groupMap = new HashMap<>();
        //消息列表sql
        Sql sql = Sqls.create("SELECT id msgId, groupId, ctAt, userId sendUserId, oprType msgOprType, msgType, content msgContent " +
                "FROM group_log $condition ");
        //消息总数sql
        Sql countSql = Sqls.create("SELECT COUNT(1) FROM group_log $condition ");
        Cnd cnd = Cnd.where("delFlag", "=", 0);
        if (Strings.isNotBlank(groupName)) {
            //模糊查询群组。赋值于群组集合map，添加查询条件
            groupName = "%" + groupName + "%";
            List<GroupInfo> query = groupInfoService.query(Cnd.where("groupName", "LIKE", groupName));
            if(query.size() > 0){
                List<String> groupIds = query.stream().map(GroupInfo::getId).collect(Collectors.toList());
                groupMap = query.stream().collect(Collectors.toMap(GroupInfo::getId, JSONObject::toJSONString));
                cnd.and("groupId", "IN", groupIds);
            }else {
                cnd.and("groupId", "IS", null);
            }
        }
        if (Strings.isNotBlank(userKeyword)) {
            //模糊查询用户。赋值于用户集合map，添加查询条件
            userKeyword = "%" + userKeyword + "%";
            List<User> query = userService.query(Cnd.where(Cnd.exps("nickName", "LIKE", userKeyword)
                    .or("userName", "LIKE", userKeyword)).and("delFlag", "=", 0));
            if(query.size() > 0){
                List<String> userIds = query.stream().map(User::getId).collect(Collectors.toList());
                userMap = userService.usersToMapJSONString(query);
                cnd.and("userId", "IN", userIds);
            }else {
                cnd.and("userId", "IS", null);
            }
        }
        if (searchDate != null && searchDate.length > 0) {
            cnd.and("ctAt", ">=", Times.d2TS(Times.D(searchDate[0])));
            cnd.and("ctAt", "<=", Times.d2TS(Times.D(searchDate[1])));
        }
        if (msgType != null) {
            cnd.and("msgType", "=", msgType);
        }
        if (oprType != null) {
            cnd.and("oprType", "=", oprType);
        }
        sql.setCondition(cnd);
        sql.appendSourceSql("ORDER BY ctAt DESC");
        countSql.setCondition(cnd);

        Pagination pagination = dbService.listPage(GroupMsgVO.class, pageNumber, pageSize, sql.toString(), countSql.toString());
        List<GroupMsgVO> groupMsgVOList = pagination.getList(GroupMsgVO.class);
        //消息带上用户、群组信息
        if(groupMsgVOList.size() > 0){
            //群组集合map中无数据，根据消息集合初始化
            if (groupMap.size() == 0){
                List<String> groupIds = groupMsgVOList.stream().map(GroupMsgVO::getGroupId).distinct().collect(Collectors.toList());
                groupMap = groupInfoService.query(Cnd.where("id", "IN", groupIds))
                        .stream().collect(Collectors.toMap(GroupInfo::getId, JSONObject::toJSONString));
            }
            //用户集合map中无数据，根据消息集合初始化
            if (userMap.size() == 0){
                List<String> userIds = groupMsgVOList.stream().map(GroupMsgVO::getSendUserId).distinct().collect(Collectors.toList());
                userMap = userService.usersToMapJSONString(userService.query(Cnd.where("id", "IN", userIds)));
            }
            //消息带上用户、群组信息
            for (GroupMsgVO groupMsgVO : groupMsgVOList) {
                GroupInfo groupInfo = JSONObject.parseObject(groupMap.get(groupMsgVO.getGroupId()), GroupInfo.class);
                User user = JSONObject.parseObject(userMap.get(groupMsgVO.getSendUserId()), User.class);
                groupMsgVO.setGroupName(groupInfo.getGroupName());
                groupMsgVO.setGroupHeadPicture(groupInfo.getGroupHeadPicture());
                groupMsgVO.setUsername(user.getUserName());
                groupMsgVO.setNickname(user.getNickName());
            }
        }
        return pagination;
    }
}
